<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="同步任务名称" prop="syncName">
        <el-input
          v-model="queryParams.syncName"
          placeholder="请输入同步任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="源数据库" prop="sourceDbId">
        <el-select v-model="queryParams.sourceDbId" placeholder="请选择源数据库" clearable>
          <el-option
            v-for="db in databaseOptions"
            :key="db.dbId"
            :label="`${db.dbName} (${db.serverName})`"
            :value="db.dbId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="目标数据库" prop="targetDbId">
        <el-select v-model="queryParams.targetDbId" placeholder="请选择目标数据库" clearable>
          <el-option
            v-for="db in databaseOptions"
            :key="db.dbId"
            :label="`${db.dbName} (${db.serverName})`"
            :value="db.dbId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="同步类型" prop="syncType">
        <el-select v-model="queryParams.syncType" placeholder="请选择同步类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_sync_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行周期" prop="execCycle">
        <el-select v-model="queryParams.execCycle" placeholder="请选择执行周期" clearable>
          <el-option
            v-for="dict in dict.type.sys_exec_cycle"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['datasync:dbsync:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['datasync:dbsync:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['datasync:dbsync:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['datasync:dbsync:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dbSyncList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="同步ID" align="center" prop="syncId" v-if="false" />
      <el-table-column label="同步任务名称" align="center" prop="syncName" />
      <el-table-column label="源数据库" align="center">
        <template slot-scope="scope">
          <el-tooltip :content="'服务器: ' + (scope.row.sourceServerName || '未知')" placement="top">
            <span>{{ scope.row.sourceDbName }}</span>
            <i class="el-icon-monitor" style="margin-left: 5px; color: #409EFF;"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="目标数据库" align="center">
        <template slot-scope="scope">
          <el-tooltip :content="'服务器: ' + (scope.row.targetServerName || '未知')" placement="top">
            <span>{{ scope.row.targetDbName }}</span>
            <i class="el-icon-monitor" style="margin-left: 5px; color: #409EFF;"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="同步类型" align="center" prop="syncType">
        <template slot-scope="scope">
          <el-tag :type="scope.row.syncType === '0' ? 'info' : 'primary'">
            {{ scope.row.syncType === '0' ? '手动同步' : '自动同步' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="同步方式" align="center" prop="syncMode">
        <template slot-scope="scope">
          <el-tag :type="scope.row.syncMode === '1' ? 'warning' : 'success'">
            {{ scope.row.syncMode === '1' ? '全量同步' : '增量同步' }}
          </el-tag>
          <el-tooltip v-if="scope.row.syncMode === '1'" content="全量同步会清空目标表数据" placement="top">
            <i class="el-icon-warning" style="color: #E6A23C; margin-left: 5px;"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="执行周期" align="center" prop="execCycle">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_exec_cycle" :value="scope.row.execCycle" />
        </template>
      </el-table-column>
      <el-table-column label="执行时间" align="center" prop="execTime" width="100" v-if="showExecTimeColumn">
        <template slot-scope="scope">
          <span>{{ scope.row.execTime || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近执行时间" align="center" prop="lastExecTime" width="160" />
      <el-table-column label="下次执行时间" align="center" prop="nextExecTime" width="160">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.execCycle !== '0' && scope.row.nextExecTime" type="success">
            {{ scope.row.nextExecTime }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['datasync:dbsync:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datasync:dbsync:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleExecute(scope.row)"
            v-hasPermi="['datasync:dbsync:execute']"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleViewLogs(scope.row)"
            v-hasPermi="['datasync:dbsync:query']"
          >日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据库同步对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="同步任务名称" prop="syncName">
              <el-input v-model="form.syncName" placeholder="请输入同步任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="同步类型" prop="syncType">
              <el-select v-model="form.syncType" placeholder="请选择同步类型">
                <el-option label="手动同步" value="0"></el-option>
                <el-option label="自动同步" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="同步方式" prop="syncMode">
              <el-select v-model="form.syncMode" placeholder="请选择同步方式">
                <el-option label="全量同步" value="1">
                  <span>全量同步</span>
                  <el-tooltip content="清空目标表数据，重新复制所有数据" placement="right">
                    <i class="el-icon-warning" style="color: #E6A23C; margin-left: 5px;"></i>
                  </el-tooltip>
                </el-option>
                <el-option label="增量同步" value="2">
                  <span>增量同步</span>
                  <el-tooltip content="仅同步变化的数据，保留目标表已有数据" placement="right">
                    <i class="el-icon-info" style="color: #409EFF; margin-left: 5px;"></i>
                  </el-tooltip>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="源数据库" prop="sourceDbId">
              <el-select v-model="form.sourceDbId" placeholder="请选择源数据库" @change="handleSourceDbChange">
                <el-option
                  v-for="db in databaseOptions"
                  :key="db.dbId"
                  :label="`${db.dbName} (${db.serverName})`"
                  :value="db.dbId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="目标数据库" prop="targetDbId">
              <el-select v-model="form.targetDbId" placeholder="请选择目标数据库">
                <el-option
                  v-for="db in databaseOptions"
                  :key="db.dbId"
                  :label="`${db.dbName} (${db.serverName})`"
                  :value="db.dbId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="同步表" prop="syncTables">
          <div>
            <el-checkbox v-model="selectAllTables" @change="handleSelectAllTables" :disabled="tableList.length === 0">选择全部表</el-checkbox>
            <el-button v-if="form.sourceDbId" type="text" @click="loadSourceTables" :loading="tableLoading">{{ tableLoading ? '加载中...' : '刷新表列表' }}</el-button>
          </div>
          <el-scrollbar style="height: 200px; margin-top: 10px;" v-if="tableList.length > 0">
            <el-checkbox-group v-model="selectedTables" @change="handleTablesChange">
              <el-checkbox v-for="table in tableList" :key="table.tableName" :label="table.tableName">
                {{ table.tableName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-scrollbar>
          <el-input v-else-if="tableLoading" value="加载中..." disabled></el-input>
          <el-input v-else-if="!form.sourceDbId" v-model="form.syncTables" type="textarea" placeholder="请先选择源数据库" disabled></el-input>
          <el-input v-else value="无可用表" disabled></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="执行周期" prop="execCycle">
              <el-select v-model="form.execCycle" placeholder="请选择执行周期">
                <el-option
                  v-for="dict in dict.type.sys_exec_cycle"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.execCycle !== '0'">
            <el-form-item label="执行时间" prop="execTime">
              <el-time-picker v-model="form.execTime" format="HH:mm" value-format="HH:mm" placeholder="选择时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 同步日志对话框 -->
    <el-dialog title="同步日志" :visible.sync="logsOpen" width="800px" append-to-body>
      <el-table v-loading="logsLoading" :data="logsList">
        <el-table-column label="执行时间" align="center" prop="execTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.execTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否成功" align="center" prop="success">
          <template slot-scope="scope">
            <el-tag :type="scope.row.success === '0' ? 'success' : 'danger'">
              {{ scope.row.success === '0' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="日志消息" align="center" prop="message" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewLogDetail(scope.row)"
            >详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logsOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 日志详情对话框 -->
    <el-dialog title="日志详情" :visible.sync="logDetailOpen" width="600px" append-to-body>
      <el-form ref="logDetailForm" :model="logDetailForm" label-width="80px">
        <el-form-item label="执行时间">
          <el-input v-model="logExecTimeStr" readonly />
        </el-form-item>
        <el-form-item label="是否成功">
          <el-tag :type="logDetailForm.success === '0' ? 'success' : 'danger'">
            {{ logDetailForm.success === '0' ? '成功' : '失败' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="日志消息">
          <el-input v-model="logDetailForm.message" type="textarea" :rows="5" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logDetailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDbSync, getDbSync, delDbSync, addDbSync, updateDbSync, executeDbSync, listSyncLogs, getSyncLogDetail } from '@/api/datasync/dbsync';
import { listDatabaseOptions } from '@/api/datasync/database';
import { getDatabaseTables } from '@/api/datasync/dbsync';

export default {
  name: "DbSync",
  dicts: ['sys_normal_disable', 'sys_sync_type', 'sys_exec_cycle'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据库同步表格数据
      dbSyncList: [],
      // 数据库选项
      databaseOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示执行时间列
      showExecTimeColumn: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        syncName: null,
        sourceDbId: null,
        targetDbId: null,
        syncType: null,
        execCycle: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        syncName: [
          { required: true, message: "同步任务名称不能为空", trigger: "blur" }
        ],
        sourceDbId: [
          { required: true, message: "源数据库不能为空", trigger: "change" }
        ],
        targetDbId: [
          { required: true, message: "目标数据库不能为空", trigger: "change" }
        ],
        syncType: [
          { required: true, message: "同步类型不能为空", trigger: "change" }
        ],
        syncMode: [
          { required: true, message: "同步方式不能为空", trigger: "change" }
        ],
        execCycle: [
          { required: true, message: "执行周期不能为空", trigger: "change" }
        ],
        execTime: [
          { required: true, message: "执行时间不能为空", trigger: "change" }
        ]
      },
      // 数据库表列表
      tableList: [],
      selectedTables: [],
      selectAllTables: false,
      tableLoading: false,
      // 同步日志相关
      logsOpen: false,
      logsLoading: true,
      logsList: [],
      logExecTimeStr: '',
      logDetailOpen: false,
      logDetailForm: {}
    };
  },
  created() {
    this.getList();
    this.getDatabaseOptions();
    // 检查是否有自动同步的任务，决定是否显示执行时间列
    this.checkAutoSyncTasks();
  },
  methods: {
    /** 查询数据库同步列表 */
    getList() {
      this.loading = true;
      listDbSync(this.queryParams).then(response => {
        this.dbSyncList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询数据库选项列表 */
    getDatabaseOptions() {
      listDatabaseOptions().then(response => {
        this.databaseOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        syncId: null,
        syncName: null,
        sourceDbId: null,
        sourceDbName: null,
        targetDbId: null,
        targetDbName: null,
        syncType: "0",
        syncMode: "1",
        syncTables: null,
        execCycle: "0",
        execTime: null,
        lastExecTime: null,
        nextExecTime: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.syncId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据库同步";
      this.tableList = [];
      this.selectedTables = [];
      this.selectAllTables = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const syncId = row.syncId || this.ids[0];
      getDbSync(syncId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据库同步";
        
        // 加载表列表
        if (this.form.sourceDbId) {
          this.loadSourceTables();
        }
      });
    },
    /** 执行同步任务按钮操作 */
    handleExecute(row) {
      const syncId = row.syncId;
      const syncType = row.syncType === '0' ? '手动' : '自动';
      const syncMode = row.syncMode === '1' ? '全量' : '增量';
      this.$modal.confirm(`您正在执行${syncType}${syncMode}同步任务"${row.syncName}"，是否继续？${row.syncMode === '1' ? '注意：全量同步将清空目标表数据！' : ''}`).then(function() {
        return executeDbSync(syncId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("执行成功");
        // 更新任务信息
        this.updateTaskInfo(syncId);
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保同步方式字段有值
          if (!this.form.syncMode) {
            this.form.syncMode = "1"; // 默认全量同步
          }
          
          if (this.form.syncId != null) {
            updateDbSync(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDbSync(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const syncIds = row.syncId || this.ids;
      this.$modal.confirm('是否确认删除数据库同步编号为"' + syncIds + '"的数据项？').then(function() {
        return delDbSync(syncIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datasync/dbsync/export', {
        ...this.queryParams
      }, `dbsync_${new Date().getTime()}.xlsx`);
    },
    // 监听源数据库选择变化
    handleSourceDbChange(dbId) {
      this.form.sourceDbId = dbId;
      if (dbId) {
        this.loadSourceTables();
      } else {
        this.tableList = [];
        this.selectedTables = [];
        this.selectAllTables = false;
      }
    },
    // 加载源数据库表列表
    loadSourceTables() {
      if (!this.form.sourceDbId) {
        return;
      }
      this.tableLoading = true;
      this.tableList = [];
      this.selectedTables = [];
      this.selectAllTables = false;

      getDatabaseTables(this.form.sourceDbId)
        .then(response => {
          this.tableList = response.data || [];
          this.tableLoading = false;

          // 如果已有选择的表，就设置为选中状态
          if (this.form.syncTables) {
            const selectedTablesArray = this.form.syncTables.split(',');
            this.selectedTables = selectedTablesArray.filter(tableName => 
              this.tableList.some(table => table.tableName === tableName)
            );
            this.selectAllTables = this.selectedTables.length === this.tableList.length;
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 处理全选/取消全选表
    handleSelectAllTables(value) {
      if (value) {
        this.selectedTables = this.tableList.map(item => item.tableName);
      } else {
        this.selectedTables = [];
      }
      this.handleTablesChange(this.selectedTables);
    },
    // 处理表选择变化
    handleTablesChange(value) {
      this.selectAllTables = value.length === this.tableList.length;
      this.form.syncTables = value.join(',');
    },
    // 查看同步日志
    handleViewLogs(row) {
      this.logsOpen = true;
      this.loadLogs(row.syncId);
    },
    // 加载同步日志
    loadLogs(syncId) {
      this.logsLoading = true;
      this.logsList = [];
      this.logExecTimeStr = '';
      this.logDetailForm = {};

      listSyncLogs(syncId).then(response => {
        this.logsList = response.rows || [];
        this.logsLoading = false;
      });
    },
    // 查看日志详情
    handleViewLogDetail(row) {
      getSyncLogDetail(row.logId).then(response => {
        this.logExecTimeStr = this.parseTime(response.data.execTime);
        this.logDetailForm = response.data;
        this.logDetailOpen = true;
      });
    },
    // 检查是否有自动同步任务
    checkAutoSyncTasks() {
      listDbSync({}).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 检查是否有设置了执行周期的任务
          const hasAutoTask = response.rows.some(item => item.execCycle !== '0');
          this.showExecTimeColumn = hasAutoTask;
        }
      });
    },
    // 更新任务信息
    updateTaskInfo(syncId) {
      getDbSync(syncId).then(response => {
        // 找到表格中相应的行并更新数据
        const index = this.dbSyncList.findIndex(item => item.syncId === syncId);
        if (index !== -1) {
          this.$set(this.dbSyncList, index, response.data);
        }
      });
    }
  }
};
</script> 